package com.lsm.sm.service.impl;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.InputStream;
import java.util.Random;

import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;

import com.lsm.sm.service.VerifyCode;
import com.lsm.sm.util.ImageUtils;

@Scope("prototype")
@Service("verifyCode")
public class VerifyCodeImpl implements VerifyCode{
	private String answer="";
	
	@Override
	public InputStream getCode() throws Exception {
		return ImageUtils.imageInstream( getCodeCarrier() );
	}

	@Override
	public Object getAnswer() {
		return answer;
	}
	
	private String createCode(){
		char[] arr = { 'a', 'b', 'c', 'd', 'e', 'f', 'd', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' };
		String str="";
		Random ranNo = new Random();
		int i = 0;
		while( str.length() < 5 ){
			 i = ranNo.nextInt( 37 );
			char c = arr[i];
			if( arr[i]>97 && ranNo.nextBoolean() ){
				c += -32;
			}
			str +=c;
		}
		return str;
	}
	
	private BufferedImage getCodeCarrier(){
		BufferedImage image =  new BufferedImage( 70, 28, BufferedImage.TYPE_INT_RGB );
		Graphics imgGrp = image.getGraphics();
		imgGrp.setColor( Color.LIGHT_GRAY );
		imgGrp.fillRect( 0, 0, 70, 28 );
		imgGrp.setFont( new Font( "Arial", Font.ITALIC+Font.BOLD, 18 ));
		imgGrp.setColor( new Color(33,38,184));
		answer = createCode();
		imgGrp.drawString(answer, 5, 20 );
		imgGrp.dispose();
		return image;
	}
	
	public static void main(String[] args) throws Exception {
		System.out.println( new VerifyCodeImpl().getCode() );
	}
}
